import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from pathlib import Path
import logging
import time

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='batch_rename.log'
)

class BatchImageRenamer:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("批量图片重命名工具")
        self.root.geometry("800x650")
        
        # 设置中文字体支持
        self.root.option_add("*Font", "SimHei 10")
        
        # 文件夹类型配置
        self.folder_types = {
            "主图": {"prefix": "Main", "replace_chars": ["主", "图", "首"]},
            "详情图": {"prefix": "Detail", "replace_chars": ["详情", "长图"]},
            "SKU图": {"prefix": "SKU", "replace_chars": ["规格", "属性"]}
        }
        
        # 延时设置(秒)
        self.delay = 0.1  # 默认延时0.1秒
        
        self.create_widgets()
        
    def create_widgets(self):
        # 选择根目录区域
        tk.Label(self.root, text="请选择一级目录\n* [主图|详情图]这些必须处于三级目录 :").pack(pady=10)
        
        self.dir_var = tk.StringVar()
        self.dir_var.set("未选择目录")
        
        entry_dir = tk.Entry(self.root, textvariable=self.dir_var, width=60, state="readonly")
        entry_dir.pack(pady=5)
        
        tk.Button(self.root, text="浏览...", command=self.select_directory).pack(pady=5)
        
        # 延时设置
        delay_frame = tk.Frame(self.root)
        delay_frame.pack(pady=10)
        
        tk.Label(delay_frame, text="操作延时(秒):").pack(side=tk.LEFT, padx=5)
        
        self.delay_var = tk.DoubleVar(value=self.delay)
        delay_scale = tk.Scale(delay_frame, from_=0, to=1, resolution=0.1, orient=tk.HORIZONTAL,
                              variable=self.delay_var, length=200)
        delay_scale.pack(side=tk.LEFT, padx=5)
        
        # 操作按钮
        self.process_btn = tk.Button(self.root, text="开始重命名", command=self.start_rename, 
                  bg="#4CAF50", fg="white", font=("SimHei", 12))
        self.process_btn.pack(pady=20)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(self.root, variable=self.progress_var, length=600, mode='determinate')
        self.progress_bar.pack(pady=10)
        
        self.progress_label = tk.Label(self.root, text="准备就绪")
        self.progress_label.pack(pady=5)
        
        # 操作日志区域
        tk.Label(self.root, text="操作日志:").pack(anchor="w", padx=20, pady=5)
        
        self.log_text = tk.Text(self.root, height=15, width=70)
        self.log_text.pack(padx=20, pady=5, fill=tk.BOTH, expand=True)
        
        scrollbar = tk.Scrollbar(self.log_text, command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.config(yscrollcommand=scrollbar.set)
        
        # 状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        status_label = tk.Label(self.root, textvariable=self.status_var, bd=1, relief=tk.SUNKEN, anchor=tk.W)
        status_label.pack(side=tk.BOTTOM, fill=tk.X)
    
    def select_directory(self):
        directory = filedialog.askdirectory(title="选择一级目录")
        if directory:
            self.dir_var.set(directory)
            self.log(f"已选择目录: {directory}")
    
    def log(self, message):
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        logging.info(message)
    
    def update_progress(self, current, total, text):
        progress = (current / total) * 100
        self.progress_var.set(progress)
        self.progress_label.config(text=f"{text} ({current}/{total})")
        self.root.update_idletasks()
    
    def start_rename(self):
        root_dir = self.dir_var.get()
        if root_dir == "未选择目录":
            messagebox.showerror("错误", "请先选择一级目录")
            return
        
        # 获取当前设置的延时
        self.delay = self.delay_var.get()
        
        try:
            self.process_btn.config(state=tk.DISABLED)
            self.status_var.set("正在处理...")
            self.root.update()
            
            self.log("开始批量重命名...")
            total_files = 0
            renamed_files = 0
            
            # 扫描所有文件以获取总数
            all_files = []
            for second_dir in os.listdir(root_dir):
                second_dir_path = os.path.join(root_dir, second_dir)
                if not os.path.isdir(second_dir_path):
                    continue
                
                for folder_type in self.folder_types.keys():
                    folder_path = os.path.join(second_dir_path, folder_type)
                    if not os.path.exists(folder_path):
                        continue
                    
                    image_files = self.get_image_files(folder_path)
                    if image_files:
                        all_files.extend([(folder_path, f) for f in image_files])
            
            total_files = len(all_files)
            self.log(f"找到 {total_files} 个图片文件需要处理")
            self.update_progress(0, total_files, "正在处理")
            
            # 处理文件
            current_count = 0
            for second_dir in os.listdir(root_dir):
                second_dir_path = os.path.join(root_dir, second_dir)
                if not os.path.isdir(second_dir_path):
                    continue
                
                self.log(f"处理二级目录: {second_dir}")
                
                for folder_type in self.folder_types.keys():
                    folder_path = os.path.join(second_dir_path, folder_type)
                    if not os.path.exists(folder_path):
                        self.log(f"未找到 {folder_type} 文件夹，跳过")
                        continue
                    
                    self.log(f"处理 {folder_type} 文件夹...")
                    
                    image_files = self.get_image_files(folder_path)
                    if not image_files:
                        self.log(f"{folder_type} 文件夹中没有找到图片文件")
                        continue
                    
                    # 按文件名中的数字排序
                    sorted_files = self.sort_files_by_number(image_files)
                    
                    # 重命名文件
                    renamed_count = self.rename_files(sorted_files, folder_path, folder_type, current_count, total_files)
                    current_count += len(sorted_files)
                    renamed_files += renamed_count
                    self.log(f"{folder_type} 文件夹处理完成，重命名了 {renamed_count} 个文件")
            
            self.progress_var.set(100)
            self.progress_label.config(text=f"处理完成! ({renamed_files}/{total_files})")
            self.status_var.set("处理完成")
            self.log(f"批量重命名完成！共处理 {total_files} 个文件，成功重命名 {renamed_files} 个文件")
            messagebox.showinfo("完成", f"批量重命名完成！\n共处理 {total_files} 个文件，成功重命名 {renamed_files} 个文件")
            
        except Exception as e:
            self.status_var.set("处理出错")
            error_msg = f"处理过程中出错: {str(e)}"
            self.log(error_msg)
            logging.error(error_msg, exc_info=True)
            messagebox.showerror("错误", f"处理过程中出错: {str(e)}")
        finally:
            self.process_btn.config(state=tk.NORMAL)
    
    def get_image_files(self, directory):
        """获取目录下的所有图片文件"""
        image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
        return [f for f in os.listdir(directory) 
                if os.path.isfile(os.path.join(directory, f)) 
                and os.path.splitext(f)[1].lower() in image_extensions]
    
    def sort_files_by_number(self, files):
        """按文件名中的数字部分排序"""
        def extract_number(filename):
            match = re.search(r'\d+', filename)
            return int(match.group()) if match else 0
        
        return sorted(files, key=extract_number)
    
    def rename_files(self, files, directory, folder_type, current_count, total_count):
        """重命名文件"""
        prefix = self.folder_types[folder_type]["prefix"]
        replace_chars = self.folder_types[folder_type]["replace_chars"]
        renamed_count = 0
        
        for index, file in enumerate(files, start=1):
            try:
                old_path = os.path.join(directory, file)
                file_name, file_ext = os.path.splitext(file)
                
                # 替换特定字符
                new_base_name = file_name
                for char in replace_chars:
                    new_base_name = new_base_name.replace(char, "-")
                
                # 构建新文件名
                new_file_name = f"{prefix}-{index:03}{file_ext}"
                
                new_path = os.path.join(directory, new_file_name)
                
                # 重命名文件
                os.rename(old_path, new_path)
                self.log(f"重命名: {file} → {new_file_name}")
                renamed_count += 1
                
                # 更新进度
                current_count += 1
                self.update_progress(current_count, total_count, f"正在处理 {folder_type}")
                
                # 添加延时
                if self.delay > 0:
                    time.sleep(self.delay)
                    
            except Exception as e:
                error_msg = f"重命名文件 {file} 时出错: {str(e)}"
                self.log(error_msg)
                logging.error(error_msg, exc_info=True)
        
        return renamed_count

if __name__ == "__main__":
    app = BatchImageRenamer()
    app.root.mainloop()